// store/model/tabs.ts
import router from "@/router";
import { defineStore } from "pinia";

export interface Tab {
  icon?: string;
  title: string;
  path: string;
  name: string;
  close: boolean;
  isKeepAlive?: boolean;
}

export const useTabsStore = defineStore("tabs", {
  state: () => ({
    tabsMenuList: [
      {
        icon: "el-icon-s-home",
        title: "首页",
        path: "/home",
        name: "home",
        close: false,
        isKeepAlive: true,
      },
    ] as Tab[],
  }),
  actions: {
    addTab(tab: Tab) {
      console.log(tab);
      if (!this.tabsMenuList.find((item) => item.path === tab.path)) {
        console.log("addTab", tab);
        this.tabsMenuList.push(tab);
      }
    },
    removeTab(path: string, isActive: boolean) {
      const index = this.tabsMenuList.findIndex((item) => item.path === path);
      if (index !== -1) {
        this.tabsMenuList.splice(index, 1);
      }
      if (isActive) {
        // 处理当前激活标签被删除的情况
        const prevTab = this.tabsMenuList[index - 1];
        if (prevTab) {
          router.push(prevTab.path);
        } else {
          router.push("/");
        }
      }
    },
    closeOther(path: string) {
      this.tabsMenuList = this.tabsMenuList.filter(
        (item) => item.path === path || !item.close
      );
    },
    removeAll() {
      this.tabsMenuList = [
        {
          icon: "el-icon-s-home",
          title: "首页",
          path: "/home",
          name: "home",
          close: false,
          isKeepAlive: true,
        },
      ];
      router.push("/");
    },
  },
  getters: {
    getTabsMenuList: (state) => state.tabsMenuList,
  },
});
